package com.vcaresolution.logistic.service;

import java.io.Serializable;

import java.util.ArrayList;
import java.util.List;

import org.apache.commons.lang.builder.ToStringBuilder;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.vcaresolution.logistic.form.VesselForm;
import com.vcaresolution.logistic.pojo.Vessel;
import com.vcaresolution.logistic.to.VesselTO;
import com.vcaresolution.util.Utils;

@Service
public class VesselServiceImpl extends BaseService implements VesselService{

	private Vessel populateVesselPojo(VesselForm vesselForm){
		Vessel vessel = new Vessel();
		BeanUtils.copyProperties(vesselForm, vessel);
		
		return vessel;
	}
	
	@Override
	@Transactional
	public void add(VesselForm vesselForm) {
		Vessel vessel = populateVesselPojo(vesselForm);
		
		vessel.setCreationdate(Utils.getCurrentDate());
		
		getDaoFactory().getUtilityDAO().add(vessel);
	}

	@Override
	@Transactional
	public void update(VesselForm vesselForm) {
		Vessel vessel = (Vessel) getDaoFactory().getUtilityDAO().findById(Vessel.class,vesselForm.getVesselid());
		vessel.setVesselname(vesselForm.getVesselname());
		
		System.out.println("====================");
		System.out.println(ToStringBuilder.reflectionToString(vessel));
		
		getDaoFactory().getUtilityDAO().update(vessel);
	}

	@Override
	@Transactional
	public void delete(VesselForm vesselForm) {
		getDaoFactory().getUtilityDAO().delete(populateVesselPojo(vesselForm));
	}

	@Override
	@Transactional
	public VesselTO findById(Serializable vesselID) {
		Vessel vessel = (Vessel) getDaoFactory().getUtilityDAO().findById(Vessel.class,vesselID);
		
		VesselTO vesselTO = new VesselTO();
		BeanUtils.copyProperties(vessel, vesselTO);
		
		return vesselTO; 
	} 

	@Override
	@Transactional
	public List<VesselTO> findByAll() {
		List<Vessel> vesselList = getDaoFactory().getUtilityDAO().findByAll(Vessel.class);
		
		List<VesselTO> vesselFormList = new ArrayList<VesselTO>();
		
		if( vesselList != null && !vesselList.isEmpty() ){
			VesselTO vesselTO = null;
			for(Vessel vessel: vesselList){
				vesselTO = new VesselTO();
				
				BeanUtils.copyProperties(vessel, vesselTO);
				vesselFormList.add(vesselTO);
			}
		}
		return vesselFormList; 
	}
	
}